package com.jy.rhin.infra.repo.notfication.message;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jy.rhin.infra.repo.notfication.message.dao.ReceiveMessageLogDao;
import com.jy.rhin.infra.repo.notfication.message.po.ReceiveMessageLogPo;
import com.jy.starter.repository.utils.MyIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.amqp.core.Message;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.util.Objects;
@Component
@Slf4j
public class ReceiveService {

    @Resource
    ReceiveMessageLogDao dao;
    @Resource
    MyIdWorker myIdWorker;

    public boolean exist(Message message) {
        return dao.existMd5(md5(new String(message.getBody())));
    }

    public void addError(long receiveTime, String messageId, Message message, Throwable throwable) {
        ReceiveMessageLogPo po = new ReceiveMessageLogPo();
        po.setId(myIdWorker.nextId());
        String msg = new String(message.getBody());
        po.setMessage(getJson(message).toJSONString());
        po.setMd5(md5(msg));
        po.setReceiveTime(new Timestamp(receiveTime));
        po.setCompleteTime(new Timestamp(System.currentTimeMillis()));
        po.setType(EReceiveLogType.ERROR);
        po.setErrorMsg(ExceptionUtils.getRootCauseMessage(throwable));

        po.addExtension(message.getMessageProperties().getReceivedRoutingKey()
                , message.getMessageProperties().getConsumerQueue()
                , messageId);
        dao.add(po);
    }

    public JSONObject getJson(Message message) {
        JSONObject json = null;
        String msg = new String(message.getBody());
        try {
            json = (JSONObject) JSON.parse(msg);
        } catch (Exception e) {
            log.warn("消息体无法解析json，自动创建json");
        }
        if (Objects.isNull(json)) {
            json = new JSONObject(1);
            json.put("message", msg);
        }
        return json;
    }

    public static String md5(String str) {
        MessageDigest md5;

        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new TranscationMessageException(TranscationMessageException.Error.ERROR_GET_MD5, e);
        }
        byte[] bytes = md5.digest(str.getBytes(StandardCharsets.UTF_8));
        StringBuilder builder = new StringBuilder();
        for (byte aByte : bytes) {
            builder.append(Integer.toHexString((0x000000FF & aByte) | 0xFFFFFF00).substring(6));
        }
        return builder.toString();
    }
}
